import { Injectable } from '@nestjs/common';
import { UpdateManagerDto } from './dto/update-manager.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Manager } from './entities/manager.entity';
import { ISignData } from '../../../interface/user.interface';
import { PatchManagerDto } from './dto/patch-manager.dto';
import { HashingService } from 'src/module/authorization/hashingService';

@Injectable()
export class ManagerService {
  constructor(
    @InjectRepository(Manager)
    private readonly managerRepositry: Repository<Manager>,
    private readonly hashService: HashingService,
  ) {}

  // 查询所有某一个地区所有个管理员列表
  async findAll(managerInfo: ISignData): Promise<Array<Manager> | any> {
    return await this.managerRepositry.find({
      where: { province: managerInfo?.province, city: managerInfo?.city },
    });
  }

  // 分页查询数据
  async skipFind(
    currentPage: number,
    pageSize: number,
    role: string,
    city: string,
    keywords?: string,
  ): Promise<Array<Manager> | any> {
    let list = null;
    if (keywords) {
      list = await this.managerRepositry
        .createQueryBuilder('manager')
        .where('manager.role = :role', { role: role })
        .andWhere('manager.isDelete = :isDelete', { isDelete: false })
        .andWhere('manager.city = :city', { city: city })
        .andWhere('manager.name LIKE :name', { name: `%${keywords}%` })
        .skip((currentPage - 1) * pageSize)
        .take(pageSize)
        .getManyAndCount();
    } else {
      list = await this.managerRepositry
        .createQueryBuilder('manager')
        .where('manager.role = :role', { role: role })
        .andWhere('manager.isDelete = :isDelete', { isDelete: false })
        .andWhere('manager.city = :city', { city: city })
        .skip((currentPage - 1) * pageSize)
        .take(pageSize)
        .getManyAndCount();
    }

    return {
      list: list[0],
      total: list[1],
      pageSize,
      currentPage,
      pages: Math.ceil(list[1] / pageSize),
    };
  }

  // 获取管理员的信息
  async findOne(id: number): Promise<Manager | any> {
    return this.managerRepositry.findOne({ where: { id } });
  }

  // 超级管理员修改信息
  patch(patchManagerInfo: PatchManagerDto) {
    const manager = this.managerRepositry.create(patchManagerInfo);
    return this.managerRepositry.save(manager);
  }

  // 管理员修改自己的信息
  update(updateManagerDto: UpdateManagerDto) {
    const manager = this.managerRepositry.create(updateManagerDto);
    return this.managerRepositry.save(manager);
  }

  // 修改密码
  async updatePassword(id, password) {
    const hashPassword = await this.hashService.hash(password);
    await this.managerRepositry.update(id, {
      password: hashPassword,
    });
    const manager = await this.managerRepositry.findOne({ where: { id } });
    return { pri_id: manager.primary_id };
  }

  // 根据id批量删除管理员，需要超级管理员才能进行, 逻辑删除
  async remove(ids: number[]) {
    ids.forEach(async (id) => {
      try {
        await this.managerRepositry
          .createQueryBuilder()
          .update(Manager)
          .set({
            isDelete: true,
          })
          .where('id = :id', { id: id })
          .execute();
      } catch (e) {
        console.log('🚀 ~ This is a result of console.log ~ ✨: 删除失败', id);
      }
      return;
    });
  }
}
